package com.woniuxy.thred.syn;

/**
 * description: UnsafeTest02 <br>
 * date: 2022/2/6 12:09 上午 <br>
 * author: shesaifei <br>
 * version: 1.0 <br>
 */

/**
 * 取钱线程不安全：
 */
public class UnsafeTest02 {
    public static void main(String[] args) {
        //账户
        Account account = new Account(100, "买车钱");
        Drawing you = new Drawing(account, 80, "zs");
        Drawing wife = new Drawing(account, 90, "happy的她");
        you.start();
        wife.start();
    }
}


//模拟取款
class Drawing extends Thread {
    //取钱的账户
    Account account;
    //取的钱数
    int drawingMoney;
    //口袋的总数
    int packetTotal;


    public Drawing(Account account, int drawingMoney, String name) {
        super(name);
        this.account = account;
        this.drawingMoney = drawingMoney;
    }


    @Override
    public void run() {
        if (account.money - drawingMoney < 0) {
            return;
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        account.money -= drawingMoney;
        packetTotal += drawingMoney;
        System.out.println(this.getName() + "-->账户余额：" + account.money);
        System.out.println(this.getName() + "-->口袋的钱为：" + packetTotal);
    }
}